<template>
  <div>
    <el-tree
      ref="refTree"
      check-strictly
      :data="list"
      :props="{ label: 'name' }"
      show-checkbox
      default-expand-all
      node-key="id"
    />
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small">取消</el-button>
        <el-button size="small" type="primary" @click="hSave">确定</el-button>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { arrayToTree } from '@/utils/index'
import { getPermissionList } from '@/api/permisson'
import { getRoleDetail, assignPerm } from '@/api/setting'
export default {
  props: {
    roleId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: []
    }
  },
  created() {
    // 调用接口，获取所有的权限点数据
    this.loadPermission()
    // 调用接口，获取当前这个角色已经具备的权限
    // 这个有个Bug,重新打开页面不会重新获取
    // 如果不用v-if就需要在父组件里面引用函数 在hAssign里面
    // this.loadPermissionByRoleId()
  },
  methods: {
    // 用户点击确定
    async hSave() {
      const permIds = this.$refs.refTree.getCheckedKeys()
      await assignPerm({ id: this.roleId, permIds: permIds })
      // 提示用户修改成功
      this.$message.success('修改成功')
      // 关闭弹层
      this.hCancel()
    },
    hCancel() {
      this.$emit('close-dialog')
    },
    async loadPermission() {
      const res = await getPermissionList()
      this.list = arrayToTree(res.data)
    },
    async loadPermissionByRoleId() {
      const res = await getRoleDetail(this.roleId)
      console.log('当前角色所有的权限点', res)
      // 回填
      this.$refs.refTree.setCheckedKeys(res.data.permIds)
    }
  }
}
</script>
